import {loadMicroApp} from 'qiankun'
import {useMicroAppStore} from '@/store'

import type  { MicroApp, ObjectType, RegistrableApp } from 'qiankun'

export async function microApplicationLoading(path: string) {
  const microStore = useMicroAppStore()
  // 根据路由地址加载当前应用配置
  const currentActiveMicroConfig = microStore.GET_FIND_MICRO_CONFIG(path)

  // 缓存的微应用列表
  const microApplicationList = microStore.microApplicationList

  console.log(' currentActiveMicroConfig ', currentActiveMicroConfig, currentActiveMicroConfig?.isRouteStart)

  // 如果没有匹配应用配置则代表跳转的不是微应用 or 微应用配置不需要路由启动的属性
  if (!currentActiveMicroConfig || !currentActiveMicroConfig.isRouteStart) {
    return
  }

  console.log('>>>> render >>>>',)

  // 根据应用配置 获取缓存的应用
  const cacheMicro = microApplicationList.get(currentActiveMicroConfig.name)

  // 判断当前挂载的是否有内容
  const containerNode = getContainerNode(currentActiveMicroConfig.container)
  const isNoTNodeContents = containerNode !== -1 && !containerNode

  // 如果没有dom节点 or 没有缓存应用配置 注册一下
  if (isNoTNodeContents || !cacheMicro) {

    console.log('>>> isNoTNodeContents :: ', isNoTNodeContents)
			
    // 如果有缓存应用配置，但是容器没有应用挂载，先卸载缓存应用再注册微应用
    if (cacheMicro) {
        cacheMicro.unmount()
        cacheMicro.unmountPromise.then(() => {
            loadRouterMicroApp(currentActiveMicroConfig)
        })
        return
    }

    // 加载应用
    loadRouterMicroApp(currentActiveMicroConfig)
  }
}

export function loadRouterMicroApp(currentApp: RegistrableApp<ObjectType>) {
  const microStore = useMicroAppStore()

  const micro = loadMicroApp(currentApp)
  micro.mountPromise.then(() => {
    // 挂载完成 设置一下vuex微应用列表
    microStore.SET_MICRO_APPLICATION_LIST(currentApp.name, micro)
  })
}

// 获取容器节点
export function getContainerNode(container: string) {
  const containerNode = container && document.querySelector(container)
  
  if (containerNode) {
      return containerNode.childNodes.length
  }
  
  return -1
}